package cn.com.headfree.welfare.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.com.headfree.base.controller.ResultData;
import cn.com.headfree.entity.isc.User;
import cn.com.headfree.welfare.entity.FlAdjustment;
import cn.com.headfree.welfare.dao.FlAdjustmentDao;

import cn.com.headfree.welfare.entity.FlIod;
import cn.com.headfree.welfare.entity.FlNcsgsxdjh;
import cn.com.headfree.welfare.service.FlAdjustmentService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.gta.edu.sdk.util.StringUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * (FlAdjustment)表服务实现类
 *
 * @author makejava
 * @since 2021-12-17 19:02:58
 */
@Service("flAdjustmentService")
public class FlAdjustmentServiceImpl implements FlAdjustmentService {
    @Resource
    private FlAdjustmentDao flAdjustmentDao;

    private static final Logger LOG = LogManager.getLogger(FlAdjustmentServiceImpl.class);

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public FlAdjustment queryById(Integer id) {
        return this.flAdjustmentDao.queryById(id);
    }

    /**
     * 查询多条数据
     *
     * @param offset 查询起始位置
     * @param limit  查询条数
     * @return 对象列表
     */
    @Override
    public List<FlAdjustment> queryAllByLimit(int offset, int limit) {
        return this.flAdjustmentDao.queryAllByLimit(offset, limit);
    }

    /**
     * 新增数据
     *
     * @param flAdjustment 实例对象
     * @return 实例对象
     */
    @Override
    public FlAdjustment insert(FlAdjustment flAdjustment) {
        this.flAdjustmentDao.insert(flAdjustment);
        return flAdjustment;
    }

    /**
     * 修改数据
     *
     * @param flAdjustment 实例对象
     * @return 实例对象
     */
    @Override
    public FlAdjustment update(FlAdjustment flAdjustment) {
        this.flAdjustmentDao.update(flAdjustment);
        return this.queryById(flAdjustment.getId());
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer id) {
        return this.flAdjustmentDao.deleteById(id) > 0;
    }


    @Override
    public ResultData importRollExcel(MultipartFile multipartFile, HttpServletRequest request, HttpServletResponse response, User loginUser,String year,String orgId){
        ResultData result = new ResultData();
        LOG.info("===========================开始导入===============================");
        //用于保存错误数据
        List<FlAdjustment> errorList=new ArrayList<>();
        //用于保存成功数据
        List<FlAdjustment> rollList=new ArrayList<>();
        //错误信息
        List<String> stringList=new ArrayList<>();
        //文件名
        String originalFilename = multipartFile.getOriginalFilename();
        if (!originalFilename.endsWith("xls") && !originalFilename.endsWith("xlsx")) {
            result.setSuccess(false);
            result.setErrorMsg("导入文件只支持xls/xlsx格式!");
            return  result;
        }
        ImportParams params = new ImportParams();
        // 表头设置为1行
        params.setHeadRows(2);
        // 标题行设置为0行，默认是0，可以不设置
        params.setTitleRows(4);
        params.setKeyIndex(0);
        try {
            List<FlAdjustment> daoExcelImportResult = ExcelImportUtil.importExcel(multipartFile.getInputStream(), FlAdjustment.class, params);
            if(daoExcelImportResult.isEmpty()){
                result.setSuccess(false);
                result.setErrorMsg("导入文件为空!");
                return  result;
            }
            //校验数据
            checkData(daoExcelImportResult,loginUser,errorList,rollList,stringList,year,orgId);
            String a="";
            if (errorList.size()>0){
                //去除最后一个字符
                a=stringList.get(0).substring(0, stringList.get(0).length() - 1);
                result.setSuccess(false);
                result.setErrorMsg(a);
                return  result;
            }
            if (errorList.isEmpty()&&rollList.isEmpty()){
                result.setSuccess(false);
                result.setErrorMsg("文件数据不能为空!");
                return  result;
            }

        }catch (Exception e){
            e.printStackTrace();
            result.setSuccess(false);
            result.setErrorMsg("导入文件分析出错!");
            return  result;
        }
        result.setSuccess(true);
        result.setErrorMsg("导入文件成功!");
        return  result;
    }

    private void checkData (List<FlAdjustment> scheduleDetailsList,User loginUser, List<FlAdjustment> errorList,List<FlAdjustment> rollList,List<String> stringList,String year,String orgId){
        String str="";
        for (int i = 0; i < scheduleDetailsList.size(); i++) {
            String a="";
            boolean flag=true;
            FlAdjustment flAdjustment=scheduleDetailsList.get(i);
            if(StringUtil.isNullOrEmpty(flAdjustment.getDwmc())){
                a+="单位名称不能为空,";
                flag=false;
            }
            if(flag) {
                flAdjustment.setOrgId(orgId);
                flAdjustment.setCreaterId(loginUser.getId());
                flAdjustment.setCreaterName(loginUser.getName());
                flAdjustment.setCreateTime(new Date());
                flAdjustment.setYearTime(year);
                flAdjustment.setDelSign(0);
                Integer insert=this.flAdjustmentDao.insert(flAdjustment);
                if (insert<=0){
                    a+="导入失败，";
                    flag=false;
                }
            }
            if (!flag){
                //去除最后一个逗号
                a=a.substring(0, a.length() - 1);
                //错误信息
                Integer b=i+1;
                str+="第"+b+"条信息导入失败提示："+a+"；";
                errorList.add(flAdjustment);
            }else {
                rollList.add(flAdjustment);
            }
        }
        stringList.add(str);
    }

    /**
     * 通过实体作为筛选条件查询
     *
     * @param flAdjustment 实例对象
     * @return 对象列表
     */
    @Override
    public PageInfo<FlAdjustment> queryAll(FlAdjustment flAdjustment){
        PageHelper.startPage(flAdjustment.getPage(), flAdjustment.getPageSize());
        flAdjustment.setDelSign(0);
        List<FlAdjustment> list =this.flAdjustmentDao.queryAll(flAdjustment);
        PageInfo<FlAdjustment> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

}
